package com.erp.base.business.service;

import java.util.Date;
import java.util.List;

import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.stereotype.Service;

import com.erp.base.base.CrudService;
import com.erp.base.business.dao.AppUserDao;
import com.erp.base.business.entity.AppUser;
import com.erp.base.common.utils.UserUtils;
import com.erp.base.system.entity.User;

@Service
public class AppUserService extends CrudService<AppUserDao, AppUser, Long> {
	@Override
	public void save(AppUser appUser) {
		User user=UserUtils.getUser();
		if (appUser.getIsNewRecord()){ 
			appUser.setCreateBy(user.getName());
			appUser.setCreateDate(new Date());
			appUser.setUpdateBy(user.getName());
			appUser.setUpdateDate(new Date());
			dao.insert(appUser);
		}else{
			appUser.setUpdateBy(user.getName());
			appUser.setUpdateDate(new Date());
			int i=dao.update(appUser);
			if(i==0){
				throw new OptimisticLockingFailureException("乐观锁错误!") ;
			}
		}
	}
	
	public void insert(AppUser appUser){
		dao.insert(appUser);
	}
	
	public void update(AppUser appUser){
		dao.update(appUser);
	}
	public AppUser loginSuccess(String username,String password){
		AppUser app=new AppUser();
		app.setUsername(username);
		app.setPassword(password);
		List<AppUser> list = dao.findList(app);
		if(list!=null&&list.size()==1){
			return list.get(0);
		}
		return null;
	}
	/**
	 * 根据用户名判断是否已经注册（username唯一）
	 * @param username
	 * @return
	 */
	public boolean isUniqueByUsername(String username){
		return findAppUserByUserName(username)==null?true:false;
	}
	/**
	 * 根据邮箱判断是否已经注册（email唯一）
	 * @param email
	 * @return
	 */
	public boolean isUniqueByEmail(String email){
		return findAppUserByEmail(email)==null?true:false;
	}
	
	public AppUser findAppUserByUserName(String username) {
		AppUser app=new AppUser();
		app.setUsername(username);
		List<AppUser> list = dao.findList(app);
		if(list!=null&&list.size()>0){
			return list.get(0);
		}
		return null;
	}

	public AppUser findAppUserByEmail(String email) {
		AppUser appUser=new AppUser();
		appUser.setEmail(email);
		List<AppUser> userList = dao.findList(appUser);
		if(userList!=null&&userList.size()==1){
			return userList.get(0);
		}
		return null;
	}

	public AppUser findAppUserByUserEmail(String username, String email) {
		AppUser appUser=new AppUser();
		appUser.setEmail(email);
		appUser.setUsername(username);
		List<AppUser> userList = dao.findList(appUser);
		if(userList!=null&&userList.size()==1){
			return userList.get(0);
		}
		return null;
	} 
	
	public AppUser getByActivateCode(String activateCode){
		return dao.getByActivateCode(activateCode);
	}
}
